package com.book.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.book.bean.Book;

@Repository
public class BookDao implements IBookDao {
	@Resource
	private SessionFactory mySessionFactory;
	
	private Session getSession() {
		return mySessionFactory.getCurrentSession();
	}
	
	@Override
	public List<Book> getAllBook() {
		String query = "from Book";
		List<Book> books = (List<Book>)getSession().createQuery(query).list();
		return books;
	}
	
	@Override
	public Book getBookById(String book_id) {
		List book = getSession().createQuery("from Book where book_id = ?").setParameter(0, book_id).list();
		if (book == null) {
			return null;
		}
		return (Book)book.get(0);
	}

	@Override
	public List<Book> getBookByName(String name) {
		String query = "from Book where book_name like '%" + name +"%'";
		List<Book> books = (List<Book>)getSession().createQuery(query).list();
		return books;
	}

	@Override
	public List<Book> getBookByPublisher(String publisher) {
		String query = "from Book where publisher like '%" + publisher +"%'";
		List<Book> books = (List<Book>)getSession().createQuery(query).list();
		return books;
	}

	@Override
	public List<Book> getBookByAuthor(String author) {
		String query = "from Book where author like '%" + author +"%'";
		List<Book> books = (List<Book>)getSession().createQuery(query).list();
		return books;
	}

	@Override
	public List<Book> getBookByKeyword(String keyword) {
		String query = "from Book where description like '%" + keyword +"%'";
		List<Book> books = (List<Book>)getSession().createQuery(query).list();
		return books;
	}
	
	@Override
	public List<Book> getBookByType(String type) {
		String query = "from Book where type_id = ?";
		List<Book> books = (List<Book>)getSession().createQuery(query).setParameter(0, type).list();
		return books;
	}
}
